<template>
  <div class="body" v-loading="loading">
    <el-button type="warning" size="small" icon="el-icon-s-promotion" @click="doUnAudit" v-if="header.status === 'audit'">&nbsp;反&nbsp;审&nbsp;</el-button>
    <template v-else>
      <el-button type="primary" size="small" icon="el-icon-check" @click="doSave">&nbsp;保&nbsp;存&nbsp;</el-button>
      <el-button type="primary" size="small" icon="el-icon-s-promotion" @click="doAudit" v-if="header.billNo">&nbsp;审&nbsp;核&nbsp;</el-button>
      <el-button type="success" size="small" icon="el-icon-refresh" @click="getBill(header.billNo, true)" v-if="header.billNo">&nbsp;恢&nbsp;复&nbsp;</el-button>
      <el-button type="danger" size="small" icon="el-icon-delete" @click="doDelete" v-if="header.billNo">&nbsp;删&nbsp;除&nbsp;</el-button>
    </template>
    <el-button type="info" size="small" icon="el-icon-back" @click="gotoList">&nbsp;返&nbsp;回&nbsp;</el-button>

    <el-form  :model="header" size="small" label-width="80px" :inline="true" class="header">
      <div class="audit_icon iconfont icon-yishenhe" v-show="header.status === 'audit'"></div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据编码">{{ header.billNo || '-' }}</el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同日期" class="header_must">
            <span v-if="header.status === 'audit'">{{ header.billDate }}</span>
            <el-date-picker size="small" v-model="header.billDate" clearable style="width: 150px;" value-format="YYYY-MM-DD" v-else />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="日期范围" class="header_must">
            <span v-if="header.status === 'audit'">{{ header.dateRange.length > 0? `${ header.dateRange[0] } ~ ${ header.dateRange[1] }`: '' }}</span>
            <el-date-picker size="small" v-model="header.dateRange" type="daterange" style="width:240px;" value-format="YYYY-MM-DD" v-else />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item prop="FPurchaseDept" label="采购部门">
            <span v-if="header.status === 'audit'">{{ header.purchaseDeptName }}</span>
            <el-select filterable @change="doChangeDept()" v-model="header.purchaseDept" size="small" clearable placeholder="请输入编码或者名称" v-else>
              <el-option v-for="item in departmentList" :key="item.key" :label="item.key + '：' + item.name" :value="item.key" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="FPurchaser" label="采购员">
            <span v-if="header.status === 'audit'">{{ header.purchaserName }}</span>
            <el-select filterable @change="doChangePurchaser" v-model="header.purchaser" size="small" clearable placeholder="请输入编码或者名称" v-else>
              <el-option v-for="item in scanEmpInfoList" :key="item.key" :label="item.key + '：' + item.name" :value="item.key" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商" class="header_must">
            <span v-if="header.status === 'audit'">{{ header.supplierName }}</span>
            <el-select v-model="header.supplierNo" filterable remote :remote-method="e => getSupplierList(e)"  @change="setSupplierValue" size="small" clearable placeholder="请输入编码或者名称" style="width: 240px" v-else>
              <el-option v-for="item in supplierList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName" :value="item.fNumber" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item prop="FCharge" label="收款方">
            <span v-if="header.status === 'audit'">{{ header.charge }}</span>
            <el-input type="text" v-model="header.charge" placeholder="请输入收款方" clearable v-else></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结算方">
            <span v-if="header.status === 'audit'">{{ header.settle }}</span>
            <el-input type="text" v-model="header.settle" placeholder="请输入结算方" clearable v-else></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注">
            <span v-if="header.status === 'audit'">{{ header.remark }}</span>
            <el-input style="width: 240px" size="small" type="text" v-model="header.remark" v-else />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div v-if="header.status !== 'audit'">
      <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteDetail">删除选择行</el-button>
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addDetail">添加分录行</el-button>
    </div>
    <el-table :data="detailList"  height="calc(100vh - 315px)" @selection-change="selectChange">
      <el-table-column label="#" width="60" align="center" type="selection" v-if="header.status !== 'audit'" ></el-table-column>
      <el-table-column width="150" prop="materialNo">
        <template #header><span class="list_must">物料编码</span></template>
        <template #default="scope" v-if="header.status !== 'audit'">
          <el-select v-model="scope.row.materialNo" :disabled="header.status === 'audit'" size="small" filterable remote :remote-method="e => getMaterialList(e)" clearable @change="setMaterialValue(scope.row, materialList)"  placeholder="编码或者名称">
            <el-option
                    v-for="item in materialList"
                    :key="item.fNumber"
                    :label="item.fNumber + ':' + item.fName + item.fSpecification"
                    :value="item.fNumber">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="物料名称(规格)" min-width="180">
        <template #default="scope"><span style="white-space: nowrap">{{ (scope.row.materialName || '') + ' ' + (scope.row.materialSpec || '') }}</span></template>
      </el-table-column>
      <el-table-column label="采购单位" width="80" prop="purchaseUnitName" align="center"></el-table-column>
      <el-table-column width="120" prop="qty" align="right">
        <template #header><span class="list_must">合同数量</span></template>
        <template #default="scope" v-if="header.status !== 'audit'">
          <el-input-number size="small" v-model="scope.row.qty" :precision="0" :controls="false" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column label="计价单位" width="80" prop="calcUnitName" align="center"></el-table-column>
      <el-table-column label="计价数量" width="120" prop="calcQty" align="right">
        <template #default="scope" v-if="header.status !== 'audit'">
          <el-input-number size="small" v-model="scope.row.calcQty" @change="updateRow(scope.row)" :controls="false" :precision="0" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column width="150" prop="deliveryDate" align="center">
        <template #header><span class="list_must">交货日期</span></template>
        <template #default="scope" v-if="header.status !== 'audit'">
          <el-date-picker size="small" v-model="scope.row.deliveryDate" clearable style="width: 100%;" value-format="YYYY-MM-DD" />
        </template>
      </el-table-column>
      <el-table-column width="120" align="right" prop="price">
        <template #header><span class="list_must">单价</span></template>
        <template #default="scope" v-if="header.status !== 'audit'">
          <el-input-number size="small" v-model="scope.row.price" @change="updateRow(scope.row)" :controls="false" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column label="含税单价" width="120" prop="taxPrice" align="right"></el-table-column>
      <el-table-column label="折扣率" align="center" prop="discountRate">
        <template #default="scope" v-if="header.status !== 'audit'">
          <el-input-number size="small" v-model="scope.row.discountRate" @change="updateRow(scope.row)" :controls="false" style="width: 100%" />
        </template>
      </el-table-column>
      <el-table-column label="金额" align="right"  width="120" prop="amount"></el-table-column>
      <el-table-column label="税率" align="center" width="120" prop="taxRateStr"></el-table-column>
      <el-table-column label="税额" align="right" width="120" prop="tax"></el-table-column>
      <el-table-column label="价税合计" width="120" align="right" prop="taxAmount"></el-table-column>
      <el-table-column width="180" align="left" prop="settleOrgName">
        <template #header><span class="list_must">结算组织</span></template>
        <template #default="scope" v-if="header.status !== 'audit'">
          <el-input type="text" size="small" v-model="scope.row.settleOrgName" />
        </template>
      </el-table-column>
      <el-table-column label="到货数量" width="120" align="right" prop="settlementQty"></el-table-column>
      <el-table-column label="结算金额" width="120" align="right" prop="settlementAmount"></el-table-column>
      <el-table-column label="操作" align="left" fixed="right" v-if="header.status !== 'audit'">
        <template #default="scope">
          <el-button type="text" size="small" style="color:var(--el-color-danger)" icon="el-icon-delete" @click="deleteRow(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted } from 'vue'
const { proxy } = getCurrentInstance()

const loading = ref(false)
const supplierLoading = ref(false)
const materialLoading = ref(false)
const supplierList = ref([])
const materialList = ref([])

const departmentList = ref([])
const empInfoList = ref([])
const scanEmpInfoList = ref([])

const header = ref({
  settle: "大连晓芹食品有限公司"
})
const detailList = ref([])
const selection = ref([])

/**
 * 获取字典
 */
const getDictionary = async () => {
  loading.value = true
  try {
    let res = await proxy.$api.getChildDictionaryListByKeys({ keys: ['department', 'empInfo'] })
    if (!res.res) return
    departmentList.value = res.department
    empInfoList.value = res.empInfo
  } finally {
    loading.value = false
  }
}

/**
 * 获取单据详细
 */
const getBill = async (billNo, reset) => {
  if (reset) {
    try {
      await proxy.$confirm('恢复后未保存数据将被清除，确定恢复吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
    } catch(e) {
      return
    }
  }
  loading.value = true
  try {
    let res = await proxy.callApi('get_pur_con', { billNo })
    if (!res.res) return
    header.value = res.header || {}
    detailList.value = res.data || []
    header.value.dateRange = [ header.value.startDate, header.value.endDate ]
    header.value.startDate = null
    header.value.endDate = null
    supplierList.value.push({ fNumber: header.value.supplierNo, fName: header.value.supplierName})
  } finally {
    loading.value = false
  }
}

/**
 * 修改采购部门
 */
const doChangeDept = init => {
  if (!init) {
    header.value.purchaser = ''
    header.value.purchaserName = ''
  }
  if (!header.value.purchaseDept) {
    scanEmpInfoList.value = []
    return
  }
  let current = departmentList.value.find(option => {
    return option.key === header.value.purchaseDept
  })
  header.value.purchaseDeptName = current.name
  let tempList = []
  empInfoList.value.forEach(k => {
    if (current.fDeptId === k.fPostDept) {
      tempList.push(k)
    }
  })
  scanEmpInfoList.value = tempList
}

/**
 * 修改采购员
 */
const doChangePurchaser = () => {
  let emp = empInfoList.value.find(option => {
    return option.key === header.value.purchaser
  })
  if (emp) {
    header.value.purchaserName = emp.name
  }
}

/**
 * 保存订单
 */
const doSave = async () => {
  if (!header.value.billDate) {
    proxy.$message.error('请输入合同日期!')
    return
  }
  if (!header.value.dateRange || header.value.dateRange.length === 0) {
    proxy.$message.error('请输入日期范围!')
    return
  }
  if (!header.value.supplierNo) {
    proxy.$message.error('请输入供应商!')
    return
  }
  if (detailList.value.length === 0) {
    proxy.$message.error('没有分录!')
    return
  }
  let dataList = []
  for(let i = 0; i < detailList.value.length; i++) {
    let data = detailList.value[i]
    if (!data.materialNo || !data.qty || !data.deliveryDate || !data.price || !data.settleOrgName) {
      proxy.$message.error(`分录行[${ i + 1 }]物料, 采购数量, 交货日期, 单价, 结算组织都必填!`)
      return
    }
    let pData = Object.assign({}, data)
    dataList.push(pData)
  }
  loading.value = true
  let param = {
    billNo: header.value.billNo,
    billDate: header.value.billDate,
    purchaseDept: header.value.purchaseDept,
    purchaseDeptName: header.value.purchaseDeptName,
    purchaser: header.value.purchaser,
    purchaserName: header.value.purchaserName,
    supplierNo: header.value.supplierNo,
    supplierName: header.value.supplierName,
    charge: header.value.charge,
    settle: header.value.settle,
    remark: header.value.remark,
    dataList
  }
  if (header.value.dateRange && header.value.dateRange.length > 0) {
    param.startDate = header.value.dateRange[0]
    param.endDate = header.value.dateRange[1]
  }
  try {
    let res = await proxy.callApi('save_pur_con', param)
    if (!res.res) return
    proxy.$message.success('保存完成!')
    return getBill(res.billNo)
  } finally {
    loading.value = false
  }
}

/**
 * 删除单据
 */
const doDelete = async () => {
  try {
    await proxy.$confirm('确定删除吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch (e) {
    return
  }
  loading.value = true
  try {
    let res = await proxy.callApi('delete_pur_con', { billNo: header.value.billNo })
    if (!res.res) return
    proxy.$message.success('已删除!')
    return gotoList()
  } finally {
    loading.value = false
  }
}

/**
 * 审核
 */
const doAudit = async () => {
  loading.value = true
  try {
    let res = await proxy.callApi('audit_pur_con', { billNo: header.value.billNo })
    if (!res.res) return
    header.value.status = 'audit'
    proxy.$message.success('审核完成!')
  } finally {
    loading.value = false
  }
}

/**
 * 反审核
 */
const doUnAudit = async () => {
  loading.value = true
  try {
    let res = await proxy.callApi('un_audit_pur_con', { billNo: header.value.billNo })
    if (!res.res) return
    header.value.status = 'save'
    proxy.$message.success('反审完成!')
  } finally {
    loading.value = false
  }
}

/**
 * 返回列表
 */
const gotoList = () => {
  return proxy.$router.push('/purchase/purConList')
}

/**
 * 获取物料列表
 */
const getMaterialList = async val => {
  materialLoading.value = true
  try {
    const res = await proxy.callApi('get_material_list', { key: val, pageSize: 20 })
    if (!res.res) return
    materialList.value = res.data
  } finally {
    materialLoading.value = false
  }
}

/**
 * 保存物料内容
 */
const setMaterialValue = (row, materialList) => {
  if (row.materialNo) {
    for(let i = 0; i < materialList.length; i++) {
      let m = materialList[i]
      if (m.fNumber === row.materialNo) {
        Object.assign(row, {
          materialNo: m.fNumber,
          materialName: m.fName,
          materialSpec: m.fSpecification,
          taxRateStr: m.FEntryTaxRate,
          taxRate: m.FEntryTaxRate.match(/(\S*)%/)[1] * 0.01,
          purchaseUnitName: m.fBaseUnitIdFName,
          calcUnitName: m.fBaseUnitIdFName,
          settlementQty: 0,
          settlementAmount: 0
        })
        break
      }
    }
  }
}

/**
 * 获取供应商列表
 */
const getSupplierList = async val => {
  supplierLoading.value = true
  try {
    const res = await proxy.callApi('get_supplier_by_key', {key: val, pageSize: 20})
    if (!res.res) return
    supplierList.value = res.data
  } finally {
    supplierLoading.value = false
  }
}

/**
 * 保存供应商内容
 */
const setSupplierValue = () => {
  header.value.supplierName = ''
  header.value.charge = ''
  if (supplierList.value && header.value.supplierNo) {
    supplierList.value.some(v => {
      if (v.fNumber === header.value.supplierNo) {
        header.value.supplierName = v.fName
        header.value.charge = v.fName
        return true
      }
    })
  }
}

/**
 * 添加分录行
 */
const addDetail = () => {
  detailList.value.push({
    settleOrgName: '大连晓芹食品有限公司'
  })
}

/**
 * 选择行处理
 */
const selectChange = data => {
  selection.value = data
}

/**
 * 删除选择行
 */
const deleteDetail = async () => {
  if (selection.value.length === 0) {
    proxy.$message.error('请选择分录行!')
    return
  }
  try {
    await proxy.$confirm('确定删除吗', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch (e) {
    return
  }
  selection.value.forEach(sel => {
    for (let i = 0; i < detailList.value.length; i++) {
      if (detailList.value[i] === sel) {
        detailList.value.splice(i, 1)
        break
      }
    }
  })
}

/**
 * 删除行
 */
const deleteRow = async idx => {
  try {
    await proxy.$confirm('确定删除吗', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch (e) {
    return
  }
  detailList.value.splice(idx, 1)
}

/**
 * 更新行数据
 */
const updateRow = row => {
  // 数量
  let calcQty = row.calcQty || 0
  // 单价
  let price = row.price || 0
  // 折扣率
  let discountRate = (row.discountRate || 100) / 100
  // 税率
  let taxRate = row.taxRate || 0

  // 含税单价
  let taxPrice = (1 + taxRate) * price
  // 总价
  let amount = calcQty * price * discountRate
  // 含税总价
  let taxAmount = taxPrice * calcQty * discountRate

  // 含税单价
  row.taxPrice = Number(taxPrice.toFixed(2))
  // 总价
  row.amount = Number(amount.toFixed(2))
  // 含税总价
  row.taxAmount = Number(taxAmount.toFixed(2))
  // 税额
  row.tax = Number((taxAmount - amount).toFixed(2))
}

onMounted(async () => {
  await getDictionary()
  let billNo = proxy.$route.query.billNo
  if (billNo) {
    await getBill(billNo)
  }
})
</script>

<style lang="scss" scoped>
.body {
  padding: 20px 0;
  .header {
    margin-top: 20px;
    position: relative;
    .header_row {
      display: flex;
      > div {
        flex-shrink: 0;
      }
      :deep(.produceDate) {
        .el-input {
          width: 100% !important;
        }
      }
    }
    .audit_icon {
      position: absolute;
      top: -10px;
      left: 60px;
      font-size: 48px;
      color: red;
    }
    .material {
      width: 100%;
    }
    .p3 {
      :deep(.el-form-item__content) {
        display: flex;
        .comment {
          margin-left: 10px;
          word-break: keep-all;
        }
      }
    }
  }
  .detail_header {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    .stat {
      display: flex;
      font-size: 15px;
      > div {
        display: flex;
        align-items: baseline;
        line-height: 32px;
        .label {
          text-align: right;
          margin-right: 5px;
          color: #aaa;
        }
        .value {
          min-width: 50px;
          margin-right: 10px;
          color: #666;
        }
      }
    }
  }
}
:deep(.header_must) {
  >label {
    &:before {
      content: '*';
      color: var(--el-color-danger);
    }
  }
}
.list_must {
  &:before {
    content: '*';
    color: var(--el-color-danger);
  }
}
</style>
